package leetcode;

import java.util.List;

/**
 * Created by baoyunfeng on 2019/8/4.
 * <p>
 * https://leetcode.com/problems/add-two-numbers/
 *
 * [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
 * [5,6,4]
 * case里包含大于int及大于long的ListNodeInt
 */
public class Add_Two_Numbers {

    public static void main(String args[]) {
        Add_Two_Numbers add_two_numbers = new Add_Two_Numbers();
        System.out.print(add_two_numbers.addTwoNumbers(add_two_numbers.parseIntToListNode(342), add_two_numbers
                .parseIntToListNode(465)));
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return parseIntToListNode(parseListNodeToInt(l1) + parseListNodeToInt(l2));
    }

    public long parseListNodeToInt(ListNode listNode) {
        long count = 0;
        int level = 0;
        while (listNode != null) {
            count += Math.pow(10, level) * listNode.val;
            level++;
            listNode = listNode.next;
        }
        return count;
    }

    public ListNode parseIntToListNode(long number) {
        long count = number;
        int level = 1;
        ListNode listNode = null;
        ListNode subNode = null;
        while (count > 0) {
            long x = (long)(count % Math.pow(10, level));
            count -= x;
            if (listNode == null) {
                listNode = new ListNode((int) (x / (Math.pow(10, level - 1))));
                subNode = listNode;
            } else {
                ListNode listNodeNext = new ListNode((int) (x / (Math.pow(10, level - 1))));
                subNode.next = listNodeNext;
                subNode = listNodeNext;
            }
            level++;
        }
        if (number == 0) {
            listNode = new ListNode(0);
        }
        return listNode;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}